//
//  YBYoungManager.m
//  WuyouTang
//
//  Created by YB007 on 2022/6/2.
//  Copyright © 2022 cat. All rights reserved.
//

#import "YBYoungManager.h"
#import "YBYoungSmall.h"
#import "YBYoungModeVC.h"

@interface YBYoungManager()

@property(nonatomic,strong)YBYoungSmall *smallPop;

@property(nonatomic,assign)BOOL ispwd;              // 是否设置密码
@property(nonatomic,assign)BOOL isstate;            // 是否开启青少年模式
@property(nonatomic,strong)NSString *promptStr;     // 小窗提示内容
@property(nonatomic,strong)NSArray *youngList;      // 青少年模式说明

@property(nonatomic,strong)NSTimer *youngTimer;
@property(nonatomic,assign)int interval;            // 定时请求间隔
@property(nonatomic,strong)NSDictionary *youngInfo; // 青少年模式详情【isuser:0-可以使用 1-时长上限 2-非规定时间 msg:对应提示】

@property(nonatomic,strong)YBAlertView *youngAlert;

@end

@implementation YBYoungManager

static YBYoungManager *_youngManager = nil;

+(instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _youngManager = [[super allocWithZone:NULL] init];
    });
    return _youngManager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    return [self shareInstance];
}
- (BOOL)youngSwitch{
    return self.isstate;
}
/// 检测
-(void)checkYoungStatus:(YoungFrom)youngFrom;{
    if ([[Config getOwnID] intValue]<=0) {
        return;
    }
    [WYNetworking postWithUrl:@"User.checkTeenagers" Dic:@{} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            
            NSDictionary *infoDic = [info firstObject];
            // 是否设置密码
            self.ispwd = [minstr([infoDic valueForKey:@"ispwd"])intValue];
            // 是否开启青少年模式
            self.isstate = [minstr([infoDic valueForKey:@"isstate"])intValue];
            // 小窗提示语
            self.promptStr = minstr([infoDic valueForKey:@"prompt"]);
            // 青少年模式说明数组
            self.youngList = [NSArray arrayWithArray:[infoDic valueForKey:@"lists"]];
            
            // 青少年模式下:定时间隔
            self.interval = [minstr([infoDic valueForKey:@"duration"])intValue];
            // 青少年模式说明【isuser:0-可以使用 1-时长上限 2-非规定时间 msg:对应提示】
            self.youngInfo = [infoDic valueForKey:@"useinfo"];
            
            [self changeBanStatus];
            // 首页、个人中心跳转页面
            if (youngFrom == YoungFrom_Home) {
                if (self.isstate == 0 && self.needShowPop == YES) {
                    // 未开启、提示开启
                    [self showYoungSmallPop];
                }else if(self.isstate == 1){
                    // 已开启、判断弹窗还是开启计时
                    [self judgeShowAlertAndNeedResetTimer:NO];
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"hideHomeVideoRed" object:nil];

                }
                self.needShowPop = NO;
            }else if(youngFrom == YoungFrom_Center){
                [self enterYoungMode];
            }
            
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        
    }];
}
#pragma mark - 开启青少年模式
-(void)enterYoungMode {
    YBYoungModeVC *modeVC = [[YBYoungModeVC alloc]init];
    modeVC.ispwd = self.ispwd;
    modeVC.isstate = self.isstate;
    modeVC.youngList = self.youngList;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:modeVC animated:YES];
}

#pragma mark - 小窗开始
-(void)showYoungSmallPop {
    self.needShowPop = NO;
    [self destroySamllPop];
    _smallPop = [YBYoungSmall showYoungPop:self.promptStr];
}
-(void)destroySamllPop {
    if (_smallPop) {
        [_smallPop removeFromSuperview];
        _smallPop = nil;
    }
}
-(void)smallEnterYoungModel;{
    [self destroySamllPop];
    [self enterYoungMode];
}
#pragma mark - 小窗结束

#pragma mark -
/// 开启-关闭
-(void)changeYoungSwitch:(int)youngSwitch youngInfo:(NSDictionary *)youngInfo;{
    self.isstate = youngSwitch;
    self.youngInfo = youngInfo;
    [self changeBanStatus];
    if (youngSwitch == 1) {
        [self judgeShowAlertAndNeedResetTimer:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:ybYoungModelSwitchChage object:nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"hideHomeVideoRed" object:nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"shopYongChange" object:nil];
    }else{
        [self destroyTimer];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"showHomeVideoRed" object:nil];

    }
}
// 改变受限状态
-(void)changeBanStatus {
    // isuser:0-可以使用 1-时长上限 2-非规定时间 msg:对应提示
    int isuser = [minstr([_youngInfo valueForKey:@"isuser"]) intValue];
    if (isuser == 0 || self.isstate == 0) {
        self.youngBan = NO;
    }else{
        self.youngBan = YES;
    }
}
/**
 * 注意:频繁切前、后台会存在可接受误差
 * 0.checkTeenagers返回请求频率、是否需要弹窗【上限、时间段】
 * 1.定时请求接口,服务端累计使用时间-->返回是否需要弹窗
 * 2.前台启动定时,后台暂停计时
 */
/// 前台
-(void)appActive;{
    if (self.isstate == NO) {
        return;
    }
    [self createTimer];
}
/// 后台
-(void)appResignActive;{
    [self destroyTimer];
}
/// 杀进程
-(void)appKilled;{
    [self destroyTimer];
}

/// 定时任务
-(void)createTimer {
    [self destroyTimer];
    /// 避免太频繁,约定最小时间10s
    if (_interval < 10) {
        _interval = 10;
    }
    _youngTimer = [NSTimer scheduledTimerWithTimeInterval:_interval target:self selector:@selector(youngTaskCount) userInfo:nil repeats:YES];
}
-(void)youngTaskCount {
    if([[Config getOwnID] intValue] <= 0){
        //用户退出、被顶掉等等销毁计时器
        [self destroyTimer];
        return;
    }
    //NSLog(@"rk_young_timer=======>");
    NSDictionary *postDic = @{@"duration":@(_interval)};
    [WYNetworking postWithUrl:@"User.reduceTeenagers" Dic:postDic Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            //NSLog(@"rk_young_timer=======>finish");
            if ([info isKindOfClass:[NSArray class]]) {
                self.youngInfo = [info firstObject];
                [self changeBanStatus];
                [self judgeShowAlertAndNeedResetTimer:NO];
            }
        }
    } Fail:^(id fail) {
        
    }];
}
-(void)destroyTimer {
    if (_youngTimer) {
        [_youngTimer invalidate];
        _youngTimer = nil;
    }
}
/// 判断是否到达限制【总时长、时间区间】
-(void)judgeShowAlertAndNeedResetTimer:(BOOL)reset {
    dispatch_async(dispatch_get_main_queue(), ^{
        // isuser:0-可以使用 1-时长上限 2-非规定时间 msg:对应提示
        int isuser = [minstr([_youngInfo valueForKey:@"isuser"]) intValue];
        NSString *youngAlert = minstr([_youngInfo valueForKey:@"msg"]);
        if (isuser > 0) {
            [[NSNotificationCenter defaultCenter]postNotificationName:ybYoungModelTimeEndEvent object:nil];
            // 提示
            [self destroyTimer];
            [self showAlert:youngAlert];
            
        }else{
            // 计时
            if (reset == YES || (reset == NO && !_youngTimer)) {
                [self createTimer];
            }
        }
    });
}

-(void)showAlert:(NSString *)alertStr {
    [self destroyAlert];
    NSDictionary *contentDic = @{
        @"title":YZMsg(@"提示"),
        @"msg":alertStr,
        @"left":YZMsg(@"知道了"),
        @"right":YZMsg(@"去关闭"),
    };
    YBWeakSelf;
    _youngAlert = [YBAlertView showAlertView:contentDic complete:^(int eventType) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (eventType == 0) {
                // 杀掉app
                [PublicObj appDestroy];
            }else{
                // 去关闭页面
                [weakSelf enterYoungMode];
            }
        });
    }];
    _youngAlert.alertFrom = AlertFrom_YoungModel;
    _youngAlert.forbidSureDismiss = YES;
}
-(void)destroyAlert {
    if (_youngAlert) {
        [_youngAlert removeFromSuperview];
        _youngAlert = nil;
    }
}

@end
